﻿using System;
using System.Net;
using System.Text;
using System.Linq;
using System.Collections.Generic;

namespace TagSearch.Plugins
{
    public class Deezer : IClass
    {
        #region JsonParseData
        private class Rootobject
        {
            public List<Datum> data { get; set; }
            public int total { get; set; }
        }

        private class Datum
        {
            public int id { get; set; }
            public string title { get; set; }
            public string link { get; set; }
            public int duration { get; set; }
            public int track_position { get; set; }
            public int disk_number { get; set; }
            public string preview { get; set; }
            public Artist artist { get; set; }
            public Album album { get; set; }
            public string type { get; set; }
        }

        private class Artist
        {
            public int id { get; set; }
            public string name { get; set; }
            public string link { get; set; }
            public string picture { get; set; }
            public string tracklist { get; set; }
            public string type { get; set; }
        }

        private class Album
        {
            public int id { get; set; }
            public string title { get; set; }
            public string cover { get; set; }
            public string tracklist { get; set; }
            public string release_date { get; set; }
            public string type { get; set; }
        }
        #endregion
        protected Dictionary<String, int> _TempTotal;
        protected Dictionary<String, List<ITag>> _TempTag;
        private object _Lock = new object();
        public Deezer()
        {
            JParse = new System.Text.Json.JsonParser();
            _TempTotal = new Dictionary<string, int>();
            _TempTag = new Dictionary<String, List<ITag>>();
        }
        public override void Search(string Name)
        {
            GetInfo(Name);
        }
        protected override void GetInfo(string Name)
        {
            lock (_Lock)
            {
                _TempTotal.Add(Name, -1);
                _TempTag.Add(Name, new List<ITag>());
            }

            var web = new IWebClient();
            web.DownloadDataCompleted += DownloadDataCompleted;
            web.DownloadDataAsync(new Uri("http://api.deezer.com/search?q=" + Uri.EscapeDataString(Name.ToLower())), new IWebClient.WebClientState(Name, 1, null));

            while (_TempTotal[Name] != _TempTag[Name].Count) { System.Threading.Thread.Sleep(1000); }

            OnEvent(Name,_TempTag[Name]);

            _TempTotal.Remove(Name);
            _TempTag.Remove(Name);
            base.GetInfo(Name);
        }
        protected void DownloadDataCompleted(dynamic sender, dynamic e)
        {
            if (e.Result != null)
            {
                string Name = e.UserState.Name;
                switch ((int)e.UserState.State)
                {
                    case 1:
                        var _RootObject = JParse.Parse<Rootobject>(Encoding.UTF8.GetString(e.Result));
                        
                        _TempTotal[Name] = _RootObject.data.Count;
                        foreach (var Json in _RootObject.data)
                        {
                            var web = new IWebClient();
                            web.DownloadDataCompleted += DownloadDataCompleted;
                            web.DownloadDataAsync(new Uri("http://api.deezer.com/track/" + Json.id), new IWebClient.WebClientState(Name, 2, new ITag()));
                            System.Threading.Thread.Sleep(250);
                        }
                        sender.Dispose();
                        break;
                    case 2:
                        var Json2 = default(Datum);
                        e.UserState.State = 3;
                        try
                        {
                            Json2 = JParse.Parse<Datum>(Encoding.UTF8.GetString(e.Result));
                            e.UserState.Tag.ID = this.GetType();
                            e.UserState.Tag.Album = Json2.album.title;
                            e.UserState.Tag.Artist = Json2.artist.name;
                            e.UserState.Tag.Title = Json2.title;
                            e.UserState.Tag.DiscNumber = Json2.disk_number;
                            e.UserState.Tag.TrackNumber = Json2.track_position;
                            e.UserState.Tag.RelaseDate = DateTime.Parse(Json2.album.release_date);
                        }
                        catch (System.FormatException) { e.UserState.Tag.RelaseDate = DateTime.MinValue; }
                        finally { sender.DownloadDataAsync(new Uri(Json2.album.cover), e.UserState); }
                        break;
                    case 3:
                        e.UserState.Tag.Cover = e.Result;
                        _TempTag[Name].Add(e.UserState.Tag);
                        sender.Dispose();
                        break;
                }
            }
        }
    }
}
